package com.jason.lightreader.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jason.lightreader.entity.LoginUser;
import com.jason.lightreader.exception.ServiceException;
import com.jason.lightreader.response.Code;
import com.jason.lightreader.response.Result;
import com.jason.lightreader.entity.User;
import com.jason.lightreader.mapper.UserMapper;
import com.jason.lightreader.service.UserService;
import com.jason.lightreader.util.JwtUtil;
import com.jason.lightreader.util.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.support.SecurityContextProvider;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.context.support.SecurityWebApplicationContextUtils;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public Result login(User user) {
        if (user.getUsername() == null || user.getPassword() == null) {
            return Result.get(Code.FAILED, "用户名或密码为空！");
        }
        //如果已经登录则返回已存在的token
        Object object = redisCache.getCacheObject("Token_" + user.getUsername());
        if (object != null) {
            Object userDetails = redisCache.getCacheObject("Details_" + user.getUsername());
            HashMap<String, Object> map = new HashMap<>();
            map.put("token", object);
            map.put("user", userDetails);
            return Result.get(Code.SUCCEED, map, "登录成功！");
        }
        //使用security进行权限校验
        UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword());
        Authentication authenticate = authenticationManager.authenticate(token);
        //获取登录用户
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        //获取用户名和详细用户对象
        String username = loginUser.getUsername();
        User userDetails = loginUser.getUser();
        //生成jwt
        String jwtToken = jwtUtil.createToken(loginUser);
        //将jwt和用户信息存入redis
        redisCache.setCacheObject("Token_" + username, jwtToken);
        redisCache.setCacheObject("Details_" + username, userDetails);
        //生成个人信息
        HashMap<String, Object> map = new HashMap<>();
        map.put("token", jwtToken);
        map.put("user", userDetails);
        return Result.get(Code.SUCCEED, map, "登录成功！");
    }

    @Override
    public Result register(User user) {
        if (Objects.isNull(user.getUsername()) || Objects.isNull(user.getPassword())) {
            throw new ServiceException(Code.ERROR, "用户名或密码不存在！");
        }
        //查询用户是否已存在
        if (this.getBaseMapper().exists(
                new LambdaQueryWrapper<>(User.class)
                        .eq(User::getUsername, user.getUsername())
        )) throw new ServiceException(Code.FAILED, "该用户已存在！请重新设置用户名。");
        //对密码进行加密
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        if (save(user)) {
            return Result.get(Code.SUCCEED, "注册成功！");
        }
        throw new ServiceException(Code.ERROR, "注册失败！未知错误。");
    }

    @Override
    public Result getSelfDetails() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        User user = loginUser.getUser();
        if (!Objects.isNull(user)) {
            return Result.get(Code.SUCCEED, user, "获取用户信息成功！");
        }
        throw new ServiceException(Code.ERROR, "获取用户信息失败！原因未知。");
    }
}
